<?php
/**
 * Created by PhpStorm.
 * User: chenzhitao
 * Date: 2018/4/17
 * Time: 下午10:43
 */

namespace App\Busi\Traits;

use Illuminate\Support\Facades\Cache;
use App\Exceptions\CaptchaException;
use App\Exceptions\ErrorCode\CaptchaError;
Trait CaptchaTrait
{
    /**
     * 设置验证码和过期时间
     *
     * @param     $key
     * @param     $captcha
     * @param int $ttl
     *
     * @return mixed
     */
    public function setCaptcha($key, $captcha, $ttl = 60*5)
    {
        return Cache::put($key, $captcha, $ttl);
    }

    /**
     * @param $key
     * @param $captcha
     *
     * @return bool
     * @throws CaptchaException
     */
    public function checkCaptcha($key, $captcha)
    {
        //测试环境绕过
        //if(in_array(env('APP_ENV'), ['test', 'dev']))    return true;
        if($this->getCaptcha($key) != $captcha) {
            throw new CaptchaException(CaptchaError::CAPTCHA_ERROR);
        }
//        Cache::forget($key);
    }

    /**
     * 获取验证码
     *
     * @param $key
     *
     * @return mixed
     */
    public function getCaptcha($key)
    {
        $code = Cache::get($key);
        if($code == false) {
            CaptchaException::touch(CaptchaError::KEY_NOT_FOUND);
        }
        return $code;
    }
}